<?php

namespace yi\di;

use Yi;
use yi\base\Component;

class ServiceLocator extends Component
{
    private $_components = [];

    private $_definitions = [];


    public function set($id, $definition)
    {
        unset($this->_components[$id]);

        if ($definition === null) {
            unset($this->_definitions[$id]);
            return;
        }

        if (is_array($definition)) {
            if (isset($definition['class'])) {
                $this->_definitions[$id] = $definition;
            }
        } else {
            throw new \Exception("Unexpected configuration type for the \"$id\" component: " . gettype($definition));
        }
    }



    public function setComponents($components)
    {
        foreach ($components as $id => $component) {
            $this->set($id, $component);
        }
    }


    public function get($id, $throwException = true)
    {
        if (isset($this->_definitions[$id])) {
            $definition = $this->_definitions[$id];

            return $this->_components[$id] = Yi::createObject($definition);
        } elseif ($throwException) {
            throw new \Exception("Unknown component ID: $id");
        }

        return null;
    }
}
